<?php

/**
 * 权限管理
 *
 * @author suning <snsnsky@gmail.com>
 */

use \Common\Bridge;

define("SITE_AUTH", 'admin-auth');
require '../../../common.inc.php';

class Auth extends lib\core\AdminAction
{
    public function doDefault()
    {
        $group = \Admin\AdminAuth::getAllGroup();

        $page = $this->app->page();
        $page->value("group", $group);
        $page->output('admin/auth.tpl');
    }

    public function doAddGroup()
    {
        $name = strval($_POST['group_name']);
        if (empty($name))
        {
            HDshowMsg('名称不能为空',['type'=>'error']);
        }

        $dbw = Bridge::pdo(Bridge::DB_ADMIN_W);

        $re = $dbw->insert("AdminGroup",['GroupName'=>$name]);
        if ($re)
        {
            $this->adminLog('添加权限组', $dbw->lastInsertId(), 'add', $name);
            HDshowMsg('添加成功');
        }
        HDshowMsg('添加失败', ['type'=>'error']);
    }

    /**
     * 编辑管理组
     */
    public function doEdit()
    {
        $id = intval($_GET['id']);

        $group = \Admin\AdminAuth::getGroupById($id);
        if (empty($group))
        {
            HDshowMsg('权限组不存在',['type'=>'error']);
        }

        if (isset($_POST['menu']))
        {
            $dbw = Bridge::pdo(Bridge::DB_ADMIN_W);

            $re = $dbw->update('AdminGroup', ['AdminAuth'=>serialize($_POST['menu'])], ['AdminGroupId'=>$id]);
            if ($re !== false)
            {
                $this->adminLog('编辑权限组', $id, 'update', serialize($_POST['menu']));
                HDshowMsg('保存成功',['url'=>ADMIN_MODULES.'admin/auth.php']);
            }
            else
            {
                HDshowMsg('保存失败',['type'=>'error']);
            }
        }

        $auth = unserialize($group['AdminAuth']);
        $auth = array_combine((array)$auth, (array)$auth);
        $menu = \Admin\Menu::getAllMenu();

        $page = $this->app->page();
        $page->value('group', $group);
        $page->value('auth', $auth);
        $page->value('menu', $menu);

        $page->output('admin/auth_edit.tpl');
    }

    /**
     * 删除管理组
     */
    public function doDel()
    {
        $id = intval($_GET['id']);

        $dbr = Bridge::pdo(Bridge::DB_ADMIN_R);
        $dbw = Bridge::pdo(Bridge::DB_ADMIN_W);

        $data = $dbr->query("select count(*) as num from AdminUser where AdminUserGroup={$id}")->fetch();
        if ($data['num'] > 0)
        {
            HDshowMsg('删除失败',['type'=>'error','desc'=>'该管理组中还有管理员，请先删除该组中的所有管理员！']);
        }
        $re = $dbw->delete("AdminGroup", ['AdminGroupId'=>$id]);
        if ($re > 0)
        {
            $this->adminLog('删除权限组', $id, 'del', $id);
            HDshowMsg('删除成功');
        }
        HDshowMsg('删除失败',['type'=>'error']);
    }
}

$app->run();